import React, { Component } from 'react'
import echarts from 'echarts'
import $ from 'jquery'
import { Table } from 'antd';
import {
    getPreviousDays,
    getTotalTime,
    formatJSON,
    getDateAndTime,
    setCookie,
    getCookie,
    delCookie,
    uuid,
    getPrevMinuteDate,
    fieldRandomData,
} from '../util/util'
import {
    currentTemperatureOption,
    currentHumidityOption,
    currentDustOption,
    dustTrendOption,
    currentYieldOption,
    currentActivationOption,
    currentPressureOption,
    yieldActTrendOption,
    outputTrendOption,
    forecastOption,
    machineParameterOption,
    primaryStatusChartOption,
    selfHealingChartOption,
    tempTrendOption,
    humiTrendOption
} from '../chart-option/option'
import '../../css/App.scss'
import { Link } from 'react-router-dom'


const equipmentStatusGantt = [
    {Create_Time: '09:00', Status: 0},
    {Create_Time: '10:00', Status: 1},
    {Create_Time: '11:28', Status: 3},
    {Create_Time: '12:00', Status: 2},
    {Create_Time: '13:30', Status: 1},
    {Create_Time: '15:55', Status: 0},
    {Create_Time: '17:27', Status: 3},
]

const webapiUrl = 'http://192.168.1.100:20002';
const webserviceUrl = 'http://192.168.1.100:20001';

class App extends Component {

    state = {
        dateString: '',
        timeString: '',
        todayOutput: 125,// 今日产量
        currentNoise: 0,// 实时噪音
        todayElectricEnergy: 67,// 今日电能
        allElectricEnergy: 557,// 累计电能
        todayGasEnergy: 89,// 今日气能
        allGasEnergy: 637,// 累计气能
        idleTime: 0,// 累计闲置时间
        runningTime: 0,// 累计运行时间
        downTime: 0,// 累计宕机时间
        inactiveTime: 0,// 累计断网时间
        lamp1: '',// 六台设备的指示灯颜色
        lamp2: '',
        lamp3: '',
        lamp4: '',
        lamp5: '',
        lamp6: '',
        activation: 0,// 稼动率
        sequecneBkg: {// 时序联动图背景图片
            sequenceCustomerBkg: 'wait',
            sequence0Bkg: 'wait',
            sequence1Bkg: 'wait',
            sequence2Bkg: 'wait',
            sequence3Bkg: 'wait',
            sequence4Bkg: 'wait',
            sequence5Bkg: 'wait',
            sequence6Bkg: 'wait',
            sequence7Bkg: 'wait',
            sequence8Bkg: 'wait',
            sequence9Bkg: 'wait',
            sequenceLogisticsBkg: 'wait',
        },

        MWH_Cycle_Time: '13',// 半成品仓循环时间
        MWH_Robot_Speed: '60',// 半成品仓机械手速度
        Load_Cycle_Time: '5',// 上料循环时间
        Load_AGV_Speed: '10',// AGV速度
        Marking_Cycle_Time: '3',// 打标循环时间
        Checking_Cycle_Time: '3',// 检测循环时间
        Checking_Speed: '60',// 机械手速度
        Unload_Cycle_Time: '6',// 下料循环时间
        Unload_Speed: '60',// 机械手速度
        FWH_Cycle_Time: '5',// 成品仓循环时间
        FWH_Robot_Speed: '400',//

        IOT1ToWebApi: 'normal',// 生产应用-webapi
        IOT1ToService: 'normal',// 生产应用-Service
        IOT1ToWinApi: 'normal',// 生产应用-winapi
        IOT5ToWebApi: 'normal',// 集成组件-webapi
        IOT5ToService: 'normal',// 集成组件-Service
        IOT5ToWinApi: 'normal',// 集成组件-winapi
        IOT5ToIOT7: 'normal',
        IOT7ToIOT9: 'normal',
        IOT9To1: 'normal',
        IOT9To2: 'normal',
        IOT9To3: 'normal',
        IOT9To4: 'normal',
        IOT9To5: 'normal',
        IOT9To6: 'normal',

        equipmentStatusGantt : [],// 甘特图
        DOMArr: [],
        orderID: '3644266205',// 订单ID
        agvColor: '#fff',
        robotColor: '#fff',
        Marking_speed: '1.2',
        forecastDownTime: '17:00-17:45',
        forecastTime: '',

        columns: [{
            key: 'parameter1',
            dataIndex: 'parameter1',
            title: '参数名',
        }, {
            key: 'value1',
            dataIndex: 'value1',
            title: '参数值',
        }, {
            key: 'parameter2',
            dataIndex: 'parameter2',
            title: '参数名',
        }, {
            key: 'value2',
            dataIndex: 'value2',
            title: '参数值',
        }, {
            key: 'parameter3',
            dataIndex: 'parameter3',
            title: '参数名',
        }, {
            key: 'value3',
            dataIndex: 'value3',
            title: '参数值',
        }],
        recipeColumns: [{
            key: 'recipe',
            title: 'RECIPE',
            dataIndex: 'recipe',
        }],
    }

    splitData (rawData) {
        let categoryData = [];
        let values = [];
        let newValues = [];
        for (let i = 0; i < rawData.length; i++) {
            categoryData.push(rawData[i].splice(0, 1)[0])
            values.push(rawData[i])
        }
        console.log(`values:${values}`)
        for (let item of values) {
            let a = item[0] + item[1];
            let b = [item[0], a, item[0], a];
            newValues.push(b);
            console.log(b)
        }
        console.log(`newValues:${newValues}`)
        return {
            categoryData: categoryData,
            values: newValues
        }
    }

    componentDidMount () {
        // 加载unity3d动画
        document.getElementById("u3d").innerHTML = '<object type="text/html" data="../../u3d.html" width="100%" height="100%"></object>';

        // 当前温度
        this.currentTemperatureChart = echarts.init(this.refs.temperature)
        this.currentTemperatureChart.setOption(currentTemperatureOption)
        // 当前湿度
        this.currentHumidityChart = echarts.init(this.refs.humidity)
        this.currentHumidityChart.setOption(currentHumidityOption)
        
        // 温度趋势
        this.tempTrendChart = echarts.init(this.refs.tempTrend)
        this.tempTrendChart.setOption(tempTrendOption)
        // 湿度趋势
        this.humiTrendChart = echarts.init(this.refs.humiTrend)
        this.humiTrendChart.setOption(humiTrendOption)
        // 当前良品率
        this.currentYieldChart = echarts.init(this.refs.yield)
        this.currentYieldChart.setOption(currentYieldOption)
        // 当前稼动率
        this.currentActivationChart = echarts.init(this.refs.activation)
        this.currentActivationChart.setOption(currentActivationOption)
        
        // 良品率、稼动率趋势
        this.yieldActTrendChart = echarts.init(this.refs.yieldActTrend)
        this.yieldActTrendChart.setOption(yieldActTrendOption)
        // 产量趋势
        this.outputTrendChart = echarts.init(this.refs.outputTrend)
        this.outputTrendChart.setOption(outputTrendOption)

        // 关键状态参数
        this.primaryStatusChart = echarts.init(this.refs.primaryStatus)
        this.primaryStatusChart.setOption(primaryStatusChartOption)
        // 自愈合参数
        this.selfHealingChart = echarts.init(this.refs.selfHealing)
        this.selfHealingChart.setOption(selfHealingChartOption)

        // 页面左侧图表调用的API接口---start
        // // 注意：温湿度趋势在同一个折线图里面，要同时设置温湿度趋势的值？？？
        // // 获取实时的温度
        // const fetchTemp = fetch(`${webapiUrl}/api/mes/ReadCurrentTemperature`)
        //     .then((response) => { return response.json()});
        // const fetchHumidity = fetch(`${webapiUrl}/api/mes/ReadCurrentDampness`)
        //     .then((response) => { return response.json()});
        // Promise.all([fetchTemp, fetchHumidity]).then((dataArr) => {
        //     // 需要将dataArr中的JSON字符串格式化为标准的JSON格式（formatJSON）？？？
        //     const tempData = dataArr[0].data;
        //     const humidityData = dataArr[1].data;
        //     const tempTrendData = this.localData('temp', tempData);
        //     const humidityTrendData = this.localData('humidity', humidityData);
        //     const xAxisData = getPrevMinuteDate();
        //     this.currentTemperatureChart.setOption({
        //         series: [{
        //             name: '温度',
        //             data: [{name: '温度', value: tempData}]
        //         }]
        //     });
        //     this.currentHumidityChart.setOption({
        //         series: [{
        //             name: '湿度',
        //             data: [{name: '湿度', value: humidityData}]
        //         }]
        //     });
        //     this.tempTrendChart.setOption({
        //         series: [{
        //             name: '温度',
        //             data: tempTrendData,
        //         }],
        //         xAxis: [{
        //             data: xAxisData,
        //         }]
        //     });
        //     this.humiTrendChart.setOption({
        //         series: [{
        //             name: '湿度',
        //             data: humidityTrendData,
        //         }],
        //         xAxis: [{
        //             data: xAxisData,
        //         }]
        //     });

        // }).catch((err) => {
        // //    如果请求发送失败，则使用模拟数据
        // });

        // 获取温湿度趋势的X轴坐标
        const xAxisData = getPrevMinuteDate();
        this.tempTrendChart.setOption({
            xAxis: [{data: xAxisData}]
        })
        // 获取实时的温度
        fetch(`${webapiUrl}/api/mes/ReadCurrentTemperature`)
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentTemperatureChart.setOption({
                    series: [{
                        name: '温度',
                        data: [{name: '温度', value: json.data}]
                    }]
                })
                // 获取温度趋势
                const tempTrendData = this.localData('temp', json.data);
                this.tempTrendChart.setOption({
                    series: [{
                        name: '温度',
                        data: tempTrendData,
                    }],
                    xAxis: [{
                        data: xAxisData,
                    }]
                })
            })
            .catch((e) => {
                const tempData = fieldRandomData().temp;
                this.currentTemperatureChart.setOption({
                    series: [{
                        name: '温度',
                        data: [{name: '温度', value: tempData}]
                    }]
                })
                const tempTrendData = this.localData('temp', tempData);
                this.tempTrendChart.setOption({
                    series: [{
                        name: '温度',
                        data: tempTrendData,
                    }],
                    xAxis: [{
                        data: xAxisData,
                    }]
                })
            })

        // 获取实时的湿度
        this.humiTrendChart.setOption({
            xAxis: [{data: xAxisData}]
        })
        fetch(`${webapiUrl}/api/mes/ReadCurrentDampness`)
            .then((response) => { return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentHumidityChart.setOption({
                    series: [{
                        name: '湿度',
                        data: [{name: '湿度', value: json.data}]
                    }]
                })
                // 获取湿度趋势
                const humidityTrendData = this.localData('humidity', json.data);
                this.humiTrendChart.setOption({
                    series: [{
                        name: '湿度',
                        data: humidityTrendData,
                    }],
                    xAxis: [{
                        data: xAxisData,
                    }]
                })
            })
            .catch((e) => {
                const humidityData = fieldRandomData().humidity;
                this.currentHumidityChart.setOption({
                    series: [{
                        name: '湿度',
                        data: [{name: '湿度', value: humidityData}]
                    }]
                })
                const humidityTrendData = this.localData('humidity', humidityData);
                this.humiTrendChart.setOption({
                    series: [{
                        name: '湿度',
                        data: humidityTrendData,
                    }],
                    xAxis: [{
                        data: xAxisData,
                    }]
                })
            })

        // 获取今日电能
        fetch(`${webapiUrl}/api/mes/ReadTodayElectricEnergy`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    todayElectricEnergy: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取累计电能
        fetch(`${webapiUrl}/api/mes/GetAllElectricEnergy`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    allElectricEnergy: json.data
                })
            })
            .catch((e) => {throw e})

        //页面左侧图表调用的API接口---end

        // 获取整条生产线的状态，绘制甘特图
        fetch(`${webapiUrl}/api/mes/GetTodayWholeEquipmentStatus`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    equipmentStatusGantt: json.data,
                });
            })
            .catch((e) => {throw e})

        //页面右侧图表调用的API接口---start
        // 获取实时的良品率
        fetch(`${webapiUrl}/api/mes/ReadCurrentYeild`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.currentYieldChart.setOption({
                    series: [{
                        name: '良品率',
                        data: [{name: '良品率', value: parseInt(json.data) * 100}]
                    }]
                })
            })
            .catch((e) => {throw e})

        // 获取近15天的良品率趋势（不包含当天）
        const chartDaysArr = getPreviousDays(15)
        this.yieldActTrendChart.setOption({
            xAxis: [{data: chartDaysArr}]
        })
        fetch(`${webapiUrl}/api/mes/GetDaysYeild`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                const trendData = this.getTrendData('yield', json.data);
                this.yieldActTrendChart.setOption({
                    series: [{
                        name: '良品率',
                        data: trendData.seriesData,
                    }],
                    xAxis: [{
                        data: trendData.xAxisData,
                    }],
                })
            })
            .catch((e) => {throw e})

        // 获取今日产量
        fetch(`${webapiUrl}/api/mes/ReadCurrentOutput`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                this.setState({
                    todayOutput: json.data
                })
            })
            .catch((e) => {throw e})

        // 获取近15天的产量趋势（不包含当天）
        this.outputTrendChart.setOption({
            xAxis: [{data: chartDaysArr}]
        })
        fetch(`${webapiUrl}/api/mes/GetDaysOutput`)
            .then((response) => {return response.json()})
            .then((json) => {
                json = JSON.parse(formatJSON(json))
                const trendData = this.getTrendData('output', json.data);
                this.outputTrendChart.setOption({
                    series: [{
                        name: '产量',
                        data: trendData.seriesData,
                    }],
                    xAxis: [{
                        data: trendData.xAxisData,
                    }],
                })
            })
            .catch((e) => {throw e})

        //页面右侧图表调用的API接口---end

        // let timeInterval = 10 * 60 * 1000
        // let dataLength = 10 * 60 / 2
        // let startTime = new Date((now.getTime() - timeInterval))

        // let temp = 25
        // let humidity = 55
        // let dust = 20
        // let tempData = []
        // let humiData = []
        // let dustData = []
        // let xAxisDataArr = []
        // let endTimeMill = startTime.getTime()

        // // 生成随机的 温度、湿度、尘埃 数据
        // function randomData () {
        //     endTimeMill = endTimeMill + 2000
        //     let a = new Date(endTimeMill)
        //     let hour = a.getHours() > 9 ? a.getHours() : `0${a.getHours()}`
        //     let minute = a.getMinutes() > 9 ? a.getMinutes() : `0${a.getMinutes()}`
        //     let second = a.getSeconds() > 9 ? a.getSeconds() : `0${a.getSeconds()}`

        //     temp = Math.round((temp + Math.random() * 6 - 3))
        //     humidity = Math.round((humidity + Math.random() * 6 - 3))
        //     dust = Math.round((dust + Math.random() * 10 - 5))
        //     if (temp > 30) {
        //         temp = 30
        //     } else if (temp < 20) {
        //         temp = 20
        //     }
        //     if (humidity > 70) {
        //         humidity = 70
        //     } else if (humidity < 40) {
        //         humidity = 40
        //     }
        //     if (dust > 30) {
        //         dust = 30
        //     } else if (dust < 10) {
        //         dust = 10
        //     }

        //     return {
        //         tempValue: temp,
        //         humiValue: humidity,
        //         xAxisData: [hour, minute].join(':'),
        //         dustValue: dust,
        //     }
        // }

        // for (let i = 0; i < dataLength; i++) {
        //     let obj = randomData()
        //     tempData.push(obj.tempValue)
        //     humiData.push(obj.humiValue)
        //     xAxisDataArr.push(obj.xAxisData)
        //     dustData.push(obj.dustValue)
        // }

        let orderIDFlag = true;
        let clock = 0

        // 定时器
        this.tempHumiTrendInterval = setInterval(function fn() {
            if (this.tempHumiTrendInterval) {
                clearInterval(this.tempHumiTrendInterval);
            }

            // 设置时钟的时间
            const dateObj = getDateAndTime()
            this.setState({
                dateString: dateObj.date,
                timeString: dateObj.time,
            })

            // 如果判断到已经过了一天，则自动更新近15天趋势的X轴标签
            // 随机生成今日电能、今日气能，自动累加累计电能和累计气能
            let now = new Date();
            let year = now.getFullYear();
            let month = now.getMonth() + 1;
            month = month > 9 ? month : `0${month}`;
            let day = now.getDate();
            day = day > 9 ? day : `0${day}`;
            let hour = now.getHours();
            let minute = now.getMinutes();
            let dateStr = `${month}-${day}`;
            let currentDate = getCookie('currentDate');
            // 判断不是当天
            if (dateStr != currentDate) {

                // 判断到不是同一天后更新的参数：良品率趋势、稼动率趋势、产量趋势
                // 获取近15天的良品率趋势（不包含当天）
                const chartDaysArr = getPreviousDays(15)
                this.yieldActTrendChart.setOption({
                    xAxis: [{data: chartDaysArr}]
                })
                fetch(`${webapiUrl}/api/mes/GetDaysYeild`)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        const trendData = this.getTrendData('yield', json.data);
                        this.yieldActTrendChart.setOption({
                            series: [{
                                name: '良品率',
                                data: trendData.seriesData,
                            }],
                            xAxis: [{
                                data: trendData.xAxisData,
                            }],
                        })
                    })
                    .catch((e) => {throw e})

                // 获取近15天的产量趋势（不包含当天）
                this.outputTrendChart.setOption({
                    xAxis: [{data: chartDaysArr}]
                })
                fetch(`${webapiUrl}/api/mes/GetDaysOutput`)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        const trendData = this.getTrendData('output', json.data);
                        this.outputTrendChart.setOption({
                            series: [{
                                name: '产量',
                                data: trendData.seriesData,
                            }],
                            xAxis: [{
                                data: trendData.xAxisData,
                            }],
                        })
                    })
                    .catch((e) => {throw e})

                setCookie({currentDate: dateStr});
                    
            }
            
            clock += 1

            if (clock == 2) {
                clock = 0
                if (hour < 17 || (hour == 17 && minute <= 30)) {
                    
                }

                // 2秒钟更新一次的参数：温度、湿度、温度趋势、湿度趋势、今日电能、累计电能、良品率、今日产量
                // 获取温湿度趋势的X轴坐标
                const xAxisData = getPrevMinuteDate();
                // 获取实时的温度
                fetch(`${webapiUrl}/api/mes/ReadCurrentTemperature`)
                    .then((response) => { return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        this.currentTemperatureChart.setOption({
                            series: [{
                                name: '温度',
                                data: [{name: '温度', value: json.data}]
                            }]
                        })
                        // 获取温度趋势
                        const tempTrendData = this.localData('temp', json.data);
                        this.tempTrendChart.setOption({
                            series: [{
                                name: '温度',
                                data: tempTrendData,
                            }],
                            xAxis: [{
                                data: xAxisData,
                            }]
                        })
                    })
                    .catch((e) => {
                        const tempData = fieldRandomData().temp;
                        this.currentTemperatureChart.setOption({
                            series: [{
                                name: '温度',
                                data: [{name: '温度', value: tempData}]
                            }]
                        })
                        const tempTrendData = this.localData('temp', tempData);
                        this.tempTrendChart.setOption({
                            series: [{
                                name: '温度',
                                data: tempTrendData,
                            }],
                            xAxis: [{
                                data: xAxisData,
                            }]
                        })
                    })

                // 获取实时的湿度
                fetch(`${webapiUrl}/api/mes/ReadCurrentDampness`)
                    .then((response) => { return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        this.currentHumidityChart.setOption({
                            series: [{
                                name: '湿度',
                                data: [{name: '湿度', value: json.data}]
                            }]
                        })
                        // 获取湿度趋势
                        const humidityTrendData = this.localData('humidity', json.data);
                        this.humiTrendChart.setOption({
                            series: [{
                                name: '湿度',
                                data: humidityTrendData,
                            }],
                            xAxis: [{
                                data: xAxisData,
                            }]
                        })
                    })
                    .catch((e) => {
                        const humidityData = fieldRandomData().humidity;
                        console.log('获取实时的湿度',humidityData);
                        this.currentHumidityChart.setOption({
                            series: [{
                                name: '湿度',
                                data: [{name: '湿度', value: humidityData}]
                            }]
                        })
                        const humidityTrendData = this.localData('humidity', humidityData);
                        this.humiTrendChart.setOption({
                            series: [{
                                name: '湿度',
                                data: humidityTrendData,
                            }],
                            xAxis: [{
                                data: xAxisData,
                            }]
                        })
                    })

                // 获取今日电能
                fetch(`${webapiUrl}/api/mes/ReadTodayElectricEnergy`)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        this.setState({
                            todayElectricEnergy: json.data
                        })
                    })
                    .catch((e) => {throw e})

                // 获取累计电能
                fetch(`${webapiUrl}/api/mes/GetAllElectricEnergy`)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        this.setState({
                            allElectricEnergy: json.data
                        })
                    })
                    .catch((e) => {throw e})
                
                // 获取实时的良品率
                fetch(`${webapiUrl}/api/mes/ReadCurrentYeild`)
                .then((response) => {return response.json()})
                .then((json) => {
                    json = JSON.parse(formatJSON(json))
                    this.currentYieldChart.setOption({
                        series: [{
                            name: '良品率',
                            data: [{name: '良品率', value: parseInt(json.data) * 100}]
                        }]
                    })
                })
                .catch((e) => {throw e})

                // 获取今日产量
                fetch(`${webapiUrl}/api/mes/ReadCurrentOutput`)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        json = JSON.parse(formatJSON(json))
                        this.setState({
                            todayOutput: json.data
                        })
                    })
                    .catch((e) => {throw e})

            }

            // 获取整条生产线的状态，绘制甘特图
            fetch(`${webapiUrl}/api/mes/GetTodayWholeEquipmentStatus`)
                .then((response) => {return response.json()})
                .then((json) => {
                    json = JSON.parse(formatJSON(json))

                    // 临时将Status修改为1，本来应该为0
                    const timeObj = this.getGantt(json.data, {Create_Time: '09:00', Status: 1});
                    const timeArr = getTotalTime(timeObj.periodArr);
                    const DOMArr = timeObj.DOMArr;
                    let idleTime = 0
                    let runningTime = 0
                    let downTime = 0
                    let inactiveTime = 0
                    for (let i of timeArr) {
                        switch (i.status) {
                            case 0:
                                idleTime = parseFloat(i.time.toFixed(2))
                                break
                            case 1:
                                runningTime = parseFloat(i.time.toFixed(2))
                                break
                            case 2:
                                downTime = parseFloat(i.time.toFixed(2))
                                break
                            case 3:
                                inactiveTime = parseFloat(i.time.toFixed(2))
                                break
                        }
                    }
                    let activation = runningTime / (idleTime + runningTime + downTime + inactiveTime)
                    activation = Math.round(activation * 100)
                    console.log(`稼动率:${activation}`)
                    this.setState({
                        idleTime,
                        runningTime,
                        downTime,
                        inactiveTime,
                        DOMArr,
                        equipmentStatusGantt: json.data,
                    })
                    this.currentActivationChart.setOption({
                        series: [{
                            name: '稼动率',
                            data: [{name: '稼动率', value: activation}]
                        }]
                    })

                })
                .catch((e) => {throw e})

            // 获取各个设备的状态
            for (let i = 1; i < 7; i++) {
                let url = `${webapiUrl}/api/mes/GetEquipment${i}Status`
                fetch(url)
                    .then((response) => {return response.json()})
                    .then((json) => {
                        let lampColor = {}
                        let lamp = ''
                        json = JSON.parse(formatJSON(json))
                        let data = parseInt(json.data)
                        switch (data) {
                            case 0:
                                lamp = '#fbff7f'
                                break
                            case 1:
                                lamp = '#7fffaa'
                                break
                            case 2:
                                lamp = '#ff4c76'
                                break
                        }
                        this.setState({
                            [`lamp${i}`]: lamp
                        })
                    })
                    .catch((e) => {throw e})
            }


            this.tempHumiTrendInterval = setInterval(fn.bind(this), 1000);
        }.bind(this), 1000);

        // 将当天的日期存入cookie，如果从cookie中读取的日期和实时获取的日期不一致，则说明不是同一天
        let now = new Date()
        let year = now.getFullYear();
        let month = now.getMonth() + 1;
        month = month > 9 ? month : `0${month}`;
        let day = now.getDate();
        day = day > 9 ? day : `0${day}`;
        let dateStr = `${month}-${day}`;
        setCookie({currentDate: dateStr});

        const daysArr = getPreviousDays(15)
        // 获取近15天的良品率趋势（不包含当天）
        this.yieldActTrendChart.setOption({
            xAxis: [{data: daysArr}]
        })
        this.outputTrendChart.setOption({
            xAxis: [{data: daysArr}],
        })

    }

    getGantt (timeArr, initValue) {
        let DOMArr = []
        let periodArr = []

        timeArr.reduce((returnedItem, nextItem) => {
            let timeStart = returnedItem.Create_Time
            let timeEnd = nextItem.Create_Time
            let arrStart = timeStart.split(':')
            let arrEnd = timeEnd.split(':')
            let secondStart = parseInt(arrStart[0]) * 60 * 60 + parseInt(arrStart[1] * 60)
            let secondEnd = parseInt(arrEnd[0] * 60 * 60 + parseInt(arrEnd[1] * 60))
            let second = secondEnd - secondStart
            let timeStr = (second / 3600).toFixed(3)
            let percent = second / 30600
            percent = `${percent * 100}%`
            let obj = {width: percent}
            switch (returnedItem.Status) {
                case 0:
                    obj.backgroundColor = '#fbff7f'
                    break
                case 1:
                    obj.backgroundColor = '#7fffaa'
                    break
                case 2:
                    obj.backgroundColor = '#ff4c76'
                    break
                case 3:
                    obj.backgroundColor = '#4f5e79'
                    break
            }
            DOMArr.push((<div style={{width: obj.width, backgroundColor: obj.backgroundColor}}></div>))
            periodArr.push({status: returnedItem.Status, time: timeStr})
            return nextItem
        }, initValue)

        return {DOMArr, periodArr}
    }

    localData(field, data) {
        const fieldStr = localStorage.getItem(field);
        let updateArr = [];

        if (fieldStr) {
            let fieldArr = fieldStr.split(',');
            if (fieldArr.length < 300) {
                const delayLength = 300 - fieldArr.length;
                switch (field) {
                    case 'temp':
                        let temp = 25;
                        for (let i = 0; i < delayLength; i++) {
                            temp = Math.round((temp + Math.random() * 6 - 3));
                            if (temp > 30) {
                                temp = 30
                            } else if (temp < 20) {
                                temp = 20
                            }
                            updateArr.push(temp);
                        }
                        updateArr.concat(fieldArr);
                        break;
                    case 'humidity':
                        let humidity = 55;
                        for (let i = 0; i < delayLength; i++) {
                            humidity = Math.round((humidity + Math.random() * 6 - 3));
                            if (humidity > 70) {
                                humidity = 70
                            } else if (humidity < 40) {
                                humidity = 40
                            }
                            updateArr.push(humidity);
                        }
                        updateArr.concat(fieldArr);
                        break;
                }
            } else {
                updateArr = fieldArr.slice(fieldArr.length - 300);
            }
        } else {
            switch (field) {
                case 'temp':
                    let temp = 25;
                    for (let i = 0; i < 300; i++) {
                        temp = Math.round((temp + Math.random() * 6 - 3));
                        if (temp > 30) {
                            temp = 30;
                        } else if (temp < 20) {
                            temp = 20;
                        }
                        updateArr.push(temp);
                    }
                    break;
                case 'humidity':
                    let humidity = 55;
                    for (let i = 0; i < 300; i++) {
                        humidity = Math.round((humidity + Math.random() * 6 - 3));
                        if (humidity > 70) {
                            humidity = 70;
                        } else if (humidity < 40) {
                            humidity = 40;
                        }
                        updateArr.push(humidity);
                    }
                    break;
            }
        }

        if (updateArr.length === 300) {
            for (let i = 0; i < 300; i++) {
                updateArr[i] = Number(updateArr[i]);
            }
            updateArr.shift();
            updateArr.push(data);
            localStorage.setItem(field, updateArr.join(','));
            return updateArr;
        }
    }

    getTrendData(field, data) {
        const daysArr = getPreviousDays(15);
        let dataArr = [];
        for (let i = 0; i < daysArr.length; i++) {
            const key = daysArr[i];
            const value = data[key];
            if (value) {
                switch (field) {
                    case 'yield':
                        dataArr.push(parseInt(value) * 100);
                        break;
                    case 'output':
                        dataArr.push(value);
                        break;
                }
                
            } else {
                switch (field) {
                    case 'yield':
                        let yieldRate = Math.round((95 + Math.random() * 6 - 3));
                        dataArr.push(yieldRate);
                        break;
                    case 'output':
                        let output = Math.round((50 + Math.random() * 6 - 3));
                        dataArr.push(output);
                        break;
                }
            }
        }
        return {
            xAxisData: daysArr,
            seriesData: dataArr,
        }
    }

    clickU3d () {
        // $('#u3d-container').css('width','50vw').css('height','50vh');
    }

    componentWillUnmount () {
        if (this.tempHumiTrendInterval) {
            clearInterval(this.tempHumiTrendInterval);
        }
    }

    render () {

        const dataSource = [{
            key: '1',
            parameter1: '温度',
            value1: '24°C',
            parameter2: '湿度',
            value2: '60%',
            parameter3: '气压',
            value3: '0.6Mpa',
        }, {
            key: '2',
            parameter1: '锡膏粘稠度',
            value1: '1000Pa.s',
            parameter2: '锡膏开封时间',
            value2: '24H',
            parameter3: '锡膏加热时间',
            value3: '0.6H',
        }, {
            key: '3',
            parameter1: '湿敏元器件烘烤时间',
            value1: '0.5H',
            parameter2: '湿敏元器件烘烤温度',
            value2: '200°C',
            parameter3: '钢网张力',
            value3: '18N',
        }, {
            key: '4',
            parameter1: '钢刀使用次数',
            value1: '20000',
            parameter2: '飞达使用次数',
            value2: '90000',
            parameter3: '钢网使用次数',
            value3: '10000',
        }, {
            key: '5',
            parameter1: '钢刀上次检测时间',
            value1: '1H',
            parameter2: '飞达上次检测时间',
            value2: '1H',
            parameter3: '钢网上次检测时间',
            value3: '1H',
        }, ];
        const recipeDataSource = [{
            key: '1',
            recipe: 'RECIPE1',
        }, {
            key: '2',
            recipe: 'RECIPE2',
        }, {
            key: '3',
            recipe: 'RECIPE3',
        }, {
            key: '4',
            recipe: 'RECIPE4',
        }, {
            key: '5',
            recipe: 'RECIPE5',
        }, ];

        return (
            <div className="App">
                <div className="App-header">
                    <span className="date">{this.state.dateString}</span>
                    <span className="title">紫光云引擎智能工厂企业云图</span>
                    <span className="time">{this.state.timeString}</span>
                </div>
                <div className="App-content">
                    <div className="content-left">
                        <div className="content-left-tempHumiDust">
                            <div ref='temperature' className="temperature"></div>
                            <div ref='humidity' className="humidity"></div>
                            {/* <div ref='dust' className="dust"></div> */}
                        </div>
                        <div className="left-center">
                            <div className="content-left-tempHumiTrend" ref='tempTrend'></div>
                            <div className="content-left-dustTrend" ref="humiTrend"></div>
                            <div className="content-left-energy" ref='energy'>
                                <div className="energy .flex-column-center">
                                    <div className="energy-title">今日电能：</div>
                                    <div className="energy-data">{this.state.todayElectricEnergy}</div>
                                </div>
                                <div className="energy">
                                    <div className="energy-title">累计电能：</div>
                                    <div className="energy-data">{this.state.allElectricEnergy}</div>
                                </div>
                            </div>
                        </div>
                        <div className="left-down">
                            <div className="content-left-lineStatus">
                                <div className="lineStatus-title">设备运转状态</div>
                                <div className="lineStatus-guide">
                                    <span><i className="idle"></i>闲置</span>
                                    <span><i className="running"></i>运行</span>
                                    <span><i className="down"></i>宕机</span>
                                </div>
                                <div className="lineStatus-gantt">
                                    <div className="dashed-line"></div>
                                    <div className="gantt">
                                        {this.state.DOMArr}
                                    </div>
                                </div>
                                <div className="lineStatus-time">
                                    <div>累计运行：<span className="running">{this.state.runningTime}</span>小时</div>
                                    <div>累计闲置：<span className="idle">{this.state.idleTime}</span>小时</div>
                                    <div>累计宕机：<span className="down">{this.state.downTime}</span>小时</div>
                                </div>
                            </div>
                            <div className="content-left-equipmentStatus">
                                <div className="orderID">订单ID：<span>{this.state.orderID}</span></div>
                                <div className="equipment-content">
                                    <div style={{width: '90%'}}>
                                        <div className="equipmentStatus">
                                            <div className="equipment">
                                                <img src="../images/material.png" className="equipment-img material"/>
                                                {/* <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp1}}>
                                                </div> */}
                                                <div className="equipment-info">
                                                    <div className='equipment-info-box'>
                                                        <span>运行状态：</span>
                                                        <div className="equipment-lamp"
                                                             style={{backgroundColor: this.state.lamp1}}>
                                                        </div>
                                                     </div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-right"></div>
                                            <div className="equipment">
                                                <img src="../images/supply.png" className="equipment-img supply"/>
                                                {/* <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp2}}></div> */}
                                                <div className="equipment-info">
                                                    <div className='equipment-info-box'>
                                                        <span>运行状态：</span>
                                                        <div className="equipment-lamp"
                                                             style={{backgroundColor: this.state.lamp2}}>
                                                        </div>
                                                     </div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-right"></div>
                                            <div className="equipment">
                                                <img src="../images/marking.png" className="equipment-img marking"/>
                                                {/* <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp3}}></div> */}
                                                <div className="equipment-info">
                                                    <div className='equipment-info-box'>
                                                        <span>运行状态：</span>
                                                        <div className="equipment-lamp"
                                                             style={{backgroundColor: this.state.lamp3}}>
                                                        </div>
                                                     </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="equipmentStatus">
                                            <div className="equipment">
                                                <img src="../images/check.png" className="equipment-img check"/>
                                                {/* <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp6}}></div> */}
                                                <div className="equipment-info">
                                                    <div className='equipment-info-box'>
                                                        <span>运行状态：</span>
                                                        <div className="equipment-lamp"
                                                             style={{backgroundColor: this.state.lamp6}}>
                                                        </div>
                                                     </div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-left"></div>
                                            <div className="equipment">
                                                <img src="../images/laying-off.png" className="equipment-img laying-off"/>
                                                {/* <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp5}}></div> */}
                                                <div className="equipment-info">
                                                    <div className='equipment-info-box'>
                                                        <span>运行状态：</span>
                                                        <div className="equipment-lamp"
                                                             style={{backgroundColor: this.state.lamp5}}>
                                                        </div>
                                                     </div>
                                                </div>
                                            </div>
                                            <div className="equipment-status-left"></div>
                                            <div className="equipment">
                                                <img src="../images/product.png" className="equipment-img product"/>
                                                {/* <div className="equipment-lamp"
                                                     style={{backgroundColor: this.state.lamp4}}></div> */}
                                                <div className="equipment-info">
                                                    <div className='equipment-info-box'>
                                                        <span>运行状态：</span>
                                                        <div className="equipment-lamp"
                                                             style={{backgroundColor: this.state.lamp4}}>
                                                        </div>
                                                     </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="equipment-status-down"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="content-center">
                        <div className="center-up" id='u3d-container'>
                            <div className='center-up-u3d' id='u3d'></div>
                            <Link to='/U3D' className='center-up-mask' onClick={this.clickU3d.bind(this)}></Link>
                        </div>

                        <div className="content-center-important">
                            <div className="primary-parameter">
                                <p className="important-title">关键参数筛选集合</p>
                                <Table
                                    columns={this.state.columns}
                                    dataSource={dataSource}
                                    pagination={false}
                                />
                            </div>
                            <div className="arrow">
                                <p>Machine Learning</p>
                                <p>Deep Learning</p>
                                <p>Statistic Learning</p>
                                <div></div>
                                <p>Sparse Coding</p>
                                <p>HMM</p>
                                <p>Data Mining</p>
                            </div>
                            <div className="recipe-combine">
                                <p className="important-title">RECIPE组合</p>
                                <Table
                                    columns={this.state.recipeColumns}
                                    dataSource={recipeDataSource}
                                    pagination={false}
                                />
                            </div>
                            <div className="best-recipe">
                                <p className="best-recipe-title">最佳RECIPE推荐算法</p>
                                <div className="primary-status" ref="primaryStatus"></div>
                                <div className="self-healing" ref="selfHealing"></div>
                            </div>
                        </div>

                    </div>
                    <div className="content-right">
                        <div className="content-right-yieldActPressure">
                            <div ref='yield' className="yield"></div>
                            <div ref='activation' className="activation"></div>
                            {/* <div ref='pressure' className="pressure"></div> */}
                        </div>
                        <div className="right-center">
                            <div className="content-right-yieldActivation" ref="yieldActTrend"></div>
                            <div className="content-right-outputNoise">
                                <div className="output">今日产量：<span>{this.state.todayOutput}</span></div>
                            </div>
                            <div className="content-right-outputTrend" ref="outputTrend"></div>
                        </div>

                        <div className="content-right-IOT flex-column-center">
                            <div className="right-IOT-1">云化生产应用</div>
                            <div className="right-IOT-2">
                                <img src={`../images/IOT-y-${this.state.IOT1ToWebApi}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT1ToService}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT1ToWinApi}.png`}/>
                            </div>
                            <div className="right-IOT-3">
                                <div className="flex-column-center">WEBAPI</div>
                                <div className="flex-column-center">WEBSERVICE</div>
                                <div className="flex-column-center">WINAPI</div>
                            </div>
                            <div className="right-IOT-4 right-IOT-2">
                                <img src={`../images/IOT-y-${this.state.IOT5ToWebApi}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT5ToService}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT5ToWinApi}.png`}/>
                            </div>
                            <div className="right-IOT-5">Integration Component</div>
                            <div className="right-IOT-6">
                                <img src={`../images/IOT-y-${this.state.IOT5ToIOT7}.png`}/>
                            </div>
                            <div className="right-IOT-7">
                                <div className="flex-row-center">SCADA Server</div>
                                <div className="flex-row-center opc-client">OPC Client</div>
                            </div>
                            <div className="right-IOT-8">
                                <img src={`../images/IOT-y-${this.state.IOT7ToIOT9}.png`}/>
                            </div>
                            <div className="right-IOT-9">OPC Server</div>
                            <div className="right-IOT-10">
                                <img src={`../images/IOT-y-${this.state.IOT9To1}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To2}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To3}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To4}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To5}.png`}/>
                                <img src={`../images/IOT-y-${this.state.IOT9To6}.png`}/>
                            </div>
                            <div className="right-IOT-11">
                                <img src={`../images/material.png`}/>
                                <img src={`../images/supply.png`}/>
                                <img src={`../images/marking.png`}/>
                                <img src={`../images/product.png`}/>
                                <img src={`../images/laying-off.png`}/>
                                <img src={`../images/check.png`}/>
                            </div>
                            <div className="IOT-guide">
                                <div><i className="IOT-normal"></i>连接正常</div>
                                <div><i className="IOT-err"></i>连接异常</div>
                            </div>
                            <div id="right-title">设备上云</div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default App